package com.example.my_flea_street.util;

import org.springframework.util.ResourceUtils;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class ImageUtil {

    public static String BASEPATH = "http://192.168.253.1:8081/";
    //base64字符串转化成图片
    public static String GenerateImage(String imgStr, String phone, String type)
    {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            String basePath = "D:/resources/"+type+"/";
            String path =basePath + type + phone + ".jpg";
            File directory = new File(basePath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
//            try {
//                image.transferTo(new File(basePath + image.getName()));
//            } catch (Exception e) {
//                // TODO
//            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return BASEPATH + type + "/" + type + phone + ".jpg";
        }
        catch (Exception e)
        {
            return null;
        }
    }
    public static void deletePic(String url,String type) {
        int position = 0;
        int count = 0;
        char[] s = url.toCharArray();
        for(int i = 0;i<s.length;i++) {
            if (s[i] == '/') {
                count++;
            }
            if (count == 3) {
                position = i;
            }

        }
        String path = "D:/resources/"+type+url.substring(position+1,s.length);
        System.out.println(path);
        File file = new File(path);
        if (file.exists())
            file.delete();
    }
}
